/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 7/9/13
 * Time: 21:14
 * To change this template use File | Settings | File Templates.
 */
var mongoose = require('mongoose');
var when = require('when');
var crypto = require('../lib/crypto.js');

var schemas = require('../schemas/index.js');
var schema = schemas['user'];

mongoose.model('user', schema);
var model = mongoose.model('user');

function create(data) {
    var deferred = when.defer();
    var Model = new model();
    Object.keys(data).forEach(function(key) {
        Model[key] = data[key];
    });
    Model.salt = Math.floor(Math.random() * 100) + Date.now().toString().slice(-4);
    Model.password = crypto.md5(crypto.md5(Model.password) + Model.salt);
    Model.save(function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

function getOneByNickname(nickname) {
    var deferred = when.defer();
    model.findOne({
        nickname : nickname
    }, function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

function getOneByMail(mail) {
    var deferred = when.defer();
    model.findOne({
        mail : mail
    }, function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

function getOneById(id) {
    var deferred = when.defer();
    model.findOne({
        _id : id
    }, function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

module.exports = {
    getOneByNickname : getOneByNickname,
    getOneByMail : getOneByMail,
    create : create,
    getOneById : getOneById
};